package com.mincko.minckotest.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.gson.Gson;

public class CropImage extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String strBlobKey = req.getParameter("cropBlobKey");
		Double dblX1 = Double.parseDouble(req.getParameter("x1"));
		Double dblY1 = Double.parseDouble(req.getParameter("y1")) / Double.parseDouble(req.getParameter("oriHeight"));
		Double dblX2 = Double.parseDouble(req.getParameter("x2")) / Double.parseDouble(req.getParameter("oriWidth"));
		Double dblY2 = Double.parseDouble(req.getParameter("y2")) / Double.parseDouble(req.getParameter("oriHeight"));;
		String jsonRet = null;
		
		BlobKey blobKey = new BlobKey(strBlobKey);
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
		Transform crop = ImagesServiceFactory.makeCrop(dblX1, dblY1, dblX2, dblY2);
		Image newImage = imagesService.applyTransform(crop, oldImage);
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file = fileService.createNewBlobFile("image/jpg");
		byte[] data = newImage.getImageData();

		FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
		// This time we write to the channel directly
		writeChannel.write(ByteBuffer.wrap(data));
		// Now finalize
		writeChannel.closeFinally();
		//if(blobKey !=null) //delete the existing blob first -- GOT ERROR here....
		//		blobstoreService.delete(blobKey);
		// Now read from the file using the Blobstore API
		blobKey = fileService.getBlobKey(file);
		String[] json = {blobKey.getKeyString()};
		jsonRet = new Gson().toJson(json); 
		res.setContentType("application/json"); 
		res.setCharacterEncoding("utf-8"); 
		res.getWriter().write(jsonRet);
	}
}